Skip to content

refactor(client): inline UserProvider.queryPreference subscribe/getSnapshot#40491

Open
ggazzo wants to merge 1 commit into
developfrom
refactor/sync-store-providers-authorization-user
Open

refactor(client): inline UserProvider.queryPreference subscribe/getSnapshot#40491
ggazzo wants to merge 1 commit into
developfrom
refactor/sync-store-providers-authorization-user

Conversation

@ggazzo
Copy link
Copy Markdown
Member

@ggazzo ggazzo commented May 12, 2026

Summary

`queryPreference` was the last context value in `UserProvider` going through `createReactiveSubscriptionFactory` — i.e., through `Tracker.autorun`. `getUserPreference` reads two sources:

  • `Users.use.getState()` (zustand, non-reactive)
  • `settings.watch(\`Accounts_Default_User_Preferences_${key}\`)` as a fallback when the user record has no override

Replace the factory call with a hand-rolled `[subscribe, getSnapshot]` pair that subscribes to `Users.use` directly and to the specific setting key via `settings.observe` — no Tracker computation, same fan-out behaviour. Same shape as #40446's migration of `ServerProvider` / `AuthenticationProvider`.

`AuthorizationProvider` still uses `createReactiveSubscriptionFactory` — the permission-check helpers (`hasPermission` / `hasRole`) read via `watch()` and will get their own plan in a follow-up. The factory file stays in place for that consumer.

Test plan

  • `yarn eslint` on the changed file: 0 errors.
  • `tsc --noEmit` on `apps/meteor` is clean.
  • Manual: open the account profile, toggle a preference (e.g. notification sound) and confirm UI updates in real time.
  • Manual: as admin change `Accounts_Default_User_Preferences_*` and confirm clients without an override pick up the new default without reload.

Task: ARCH-2141

Summary by CodeRabbit

  • Bug Fixes

    • Improved user preference synchronization so personal and admin-default preference changes are reflected in real-time across the app.
  • Chores

    • Stabilized internal preference handling to reduce inconsistencies and ensure reliable updates when system configuration changes occur.

Review Change Stack

@ggazzo ggazzo requested a review from a team as a code owner May 12, 2026 13:10
@ggazzo
Copy link
Copy Markdown
Member Author

ggazzo commented May 12, 2026

/jira ARCH-2116

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented May 12, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fc92f71d-5d15-4776-b5c9-82d86c710f86

📥 Commits

Reviewing files that changed from the base of the PR and between d1d2090 and defb98e.

📒 Files selected for processing (1)
  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/meteor/client/providers/UserProvider/UserProvider.tsx

Walkthrough

The UserProvider refactors its queryPreference to accept string | ObjectId, replaces the factory-based subscription with an inline implementation that subscribes to Users.use and observes settings.observe("Accounts_Default_User_Preferences_${String(key)}"), unsubscribes both on cleanup, and reads snapshots via getUserPreference(userId, String(key), defaultValue).

Changes

User Preference Subscription Enhancement

Layer / File(s) Summary
queryPreference subscription implementation
apps/meteor/client/providers/UserProvider/UserProvider.tsx
MongoDB ObjectId import added. Provider imports updated: createReactiveSubscriptionFactory removed, getDdpSdk/settings adjusted. queryPreference now accepts key: string | ObjectId, subscribes to Users.use and observes settings.observe(Accounts_Default_User_Preferences_${String(key)}), returns cleanup that unsubscribes both, and snapshots via getUserPreference(userId, String(key), defaultValue).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • RocketChat/Rocket.Chat#40446: Also modifies UserProvider.queryPreference subscription/snapshot approach; this PR replaces the factory with an inline dual-subscribe and expands key type.

Suggested reviewers

  • tassoevan

Suggested labels

type: chore

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: refactoring UserProvider.queryPreference to use an inline subscribe/getSnapshot implementation instead of the factory function.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • ARCH-2141: Request failed with status code 401

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
apps/meteor/client/providers/UserProvider/UserProvider.tsx (2)

147-149: 💤 Low value

Consider removing implementation comment per coding guidelines.

The comment explains the internal behavior of getUserPreference and why the settings subscription is needed. While this is architecturally useful context, the coding guideline for TypeScript files asks to avoid code comments in implementation.

Consider whether this comment adds sufficient value to warrant an exception, or if the behavior could be documented elsewhere (e.g., in PR description, commit message, or the getUserPreference function itself).

As per coding guidelines: "Avoid code comments in the implementation" for **/*.{ts,tsx,js}.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/client/providers/UserProvider/UserProvider.tsx` around lines 147
- 149, Remove the implementation comment explaining getUserPreference's fallback
and the settings.watch subscription from UserProvider.tsx; either delete it or
relocate that rationale to the getUserPreference function's JSDoc or the
PR/commit message. Specifically, update the comment near the settings.watch
invocation in the UserProvider component and ensure any necessary documentation
lives on getUserPreference (its function comment) or external documentation so
the implementation file follows the "avoid code comments in implementation"
guideline.

141-158: 💤 Low value

Consider using .toString() for explicit ObjectId conversion.

The code uses String(key) to convert ObjectId | string to string (lines 150, 156). While String() coercion works, using String(key) on mixed types is less explicit than checking the type and calling .toString() when needed, or using a type guard.

📝 More explicit conversion approach
-			const subscribe = (onStoreChange: () => void): (() => void) => {
+			const keyStr = String(key);
+			const subscribe = (onStoreChange: () => void): (() => void) => {
 				const unsubUsers = Users.use.subscribe(onStoreChange);
 				// getUserPreference falls back to settings.watch(`Accounts_Default_User_Preferences_${key}`)
 				// when the user record has no override. Subscribe to that specific
 				// setting key so admin-side default changes still propagate.
-				const unsubSettings = settings.observe(`Accounts_Default_User_Preferences_${String(key)}`, onStoreChange);
+				const unsubSettings = settings.observe(`Accounts_Default_User_Preferences_${keyStr}`, onStoreChange);
 				return () => {
 					unsubUsers();
 					unsubSettings();
 				};
 			};
-			const getSnapshot = (): T | undefined => getUserPreference(userId, String(key), defaultValue);
+			const getSnapshot = (): T | undefined => getUserPreference(userId, keyStr, defaultValue);
 			return [subscribe, getSnapshot];

This hoists the conversion to clarify that both subscribe and getSnapshot use the same string representation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/client/providers/UserProvider/UserProvider.tsx` around lines 141
- 158, The queryPreference helper currently uses String(key) in both subscribe
and getSnapshot; change this to compute a single stringKey by checking the type
of key and calling key.toString() when key is an ObjectId (or otherwise using
the existing string), then use stringKey in Users.use.subscribe/settings.observe
and in getUserPreference(userId, stringKey, defaultValue) so the conversion is
explicit and consistent across subscribe and getSnapshot (refer to
queryPreference, subscribe, getSnapshot, getUserPreference, settings.observe,
and Users.use.subscribe).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/meteor/client/providers/UserProvider/UserProvider.tsx`:
- Around line 147-149: Remove the implementation comment explaining
getUserPreference's fallback and the settings.watch subscription from
UserProvider.tsx; either delete it or relocate that rationale to the
getUserPreference function's JSDoc or the PR/commit message. Specifically,
update the comment near the settings.watch invocation in the UserProvider
component and ensure any necessary documentation lives on getUserPreference (its
function comment) or external documentation so the implementation file follows
the "avoid code comments in implementation" guideline.
- Around line 141-158: The queryPreference helper currently uses String(key) in
both subscribe and getSnapshot; change this to compute a single stringKey by
checking the type of key and calling key.toString() when key is an ObjectId (or
otherwise using the existing string), then use stringKey in
Users.use.subscribe/settings.observe and in getUserPreference(userId, stringKey,
defaultValue) so the conversion is explicit and consistent across subscribe and
getSnapshot (refer to queryPreference, subscribe, getSnapshot,
getUserPreference, settings.observe, and Users.use.subscribe).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8ecb3023-661b-4960-babd-3838702b886a

📥 Commits

Reviewing files that changed from the base of the PR and between 6b2afb3 and d1d2090.

📒 Files selected for processing (1)
  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
🧠 Learnings (2)
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.

Applied to files:

  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/client/providers/UserProvider/UserProvider.tsx
🔇 Additional comments (2)
apps/meteor/client/providers/UserProvider/UserProvider.tsx (2)

150-150: settings.observe API exists and correctly returns a cleanup function.

The observe(key: string, callback: SettingCallback): () => void signature confirms the code on line 150 properly captures the unsubscribe function.


156-156: getUserPreference explicitly handles undefined userId.

The function overloads document that undefined is an accepted parameter type (lines 12, 19, 27, 35-39), and the implementation uses optional chaining (user?.settings?.preferences?.[key]) to safely handle undefined values with proper fallback behavior to defaultValue or settings.watch(). No runtime errors will occur when userId is undefined.

			> Likely an incorrect or invalid review comment.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.60%. Comparing base (0ae9ab0) to head (defb98e).
⚠️ Report is 4 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40491      +/-   ##
===========================================
- Coverage    69.61%   69.60%   -0.01%     
===========================================
  Files         3324     3324              
  Lines       122651   122664      +13     
  Branches     21864    21854      -10     
===========================================
+ Hits         85381    85386       +5     
+ Misses       33939    33933       -6     
- Partials      3331     3345      +14     
Flag Coverage Δ
e2e 59.16% <100.00%> (-0.03%) ⬇️
e2e-api 46.25% <ø> (+0.01%) ⬆️
unit 70.31% <ø> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…apshot

queryPreference was the last context value in UserProvider going through
createReactiveSubscriptionFactory — i.e., through Tracker.autorun.
getUserPreference reads two sources:
- Users.use.getState() (zustand, non-reactive)
- settings.watch(`Accounts_Default_User_Preferences_${key}`) as a fallback
  when the user record has no override

Replace the factory call with a hand-rolled [subscribe, getSnapshot] pair
that subscribes to Users.use directly and to the specific setting key via
settings.observe — no Tracker computation, same fan-out behaviour. Same
shape as the useSyncExternalStore migration #40446 did for ServerProvider /
AuthenticationProvider.

AuthorizationProvider still uses createReactiveSubscriptionFactory; the
permission-check helpers (hasPermission / hasRole) read via watch() and
will get their own plan in a follow-up. The factory file stays in place
for that consumer.
@ggazzo ggazzo force-pushed the refactor/sync-store-providers-authorization-user branch from d1d2090 to defb98e Compare May 14, 2026 12:33
@ggazzo ggazzo added this to the 8.5.0 milestone May 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant